package com.allenkerr.service.impl;

import java.util.concurrent.CountDownLatch;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.allenkerr.dao.PersonRepository;
import com.allenkerr.model.Person;
import com.allenkerr.service.IAsyncService;

/**
 * @author 小柯
 * @date 2017/12/4
 */
@Service
public class AsyncServiceImpl implements IAsyncService {

  @Autowired
  private PersonRepository personDao;

  private static final Logger logger = LoggerFactory.getLogger(AsyncServiceImpl.class);

  @Async
  @Override
  public void testCountDownLatch(long sleepTime, CountDownLatch countDownLatch) {
    logger.info("testCountDownLatch method start, sleep {} ms.", sleepTime);
    try {
      Thread.sleep(sleepTime);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    logger.info("sleep complete.");
    countDownLatch.countDown();
  }

  @Async
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void testCountDownLatch(long sleepTime, CountDownLatch countDownLatch, String uuid) {
    logger.info("testCountDownLatch method start, sleep {} ms.", sleepTime);
    try {
      Thread.sleep(sleepTime);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    logger.info("sleep complete.");

    //更新 person，疑问：数据库是否能查到刚刚插入的数据
    Person person = personDao.findFirstByUuid(uuid);
    if (person == null) {
      logger.error("Can't find person by uuid: {}.", uuid);
      countDownLatch.countDown();
      return;
    }
    //设置密码
    person.setPassword("12345678");
    //显式更新一下，非必要
//    Person save = personDao.save(person);
//    System.out.println("save = " + save);

    Person saveAndFlush = personDao.saveAndFlush(person);
    System.out.println("saveAndFlush = " + saveAndFlush);

    logger.info("update complete.");

    countDownLatch.countDown();
  }

}
